@echo off
echo ========================================
echo        Jan Backend Server Startup
echo ========================================
echo.

REM Set project paths
set PROJECT_ROOT=%~dp0
set JAR_FILE=%PROJECT_ROOT%resource-server\target\resource-server.jar

echo Current project directory: %PROJECT_ROOT%
echo JAR file location: %JAR_FILE%
echo.

REM Check if user wants to force rebuild
set /p FORCE_BUILD="Force rebuild? (y/N): "
if /i "%FORCE_BUILD%"=="y" goto :full_build

REM Check if JAR file exists
if not exist "%JAR_FILE%" (
    echo JAR file not found. Building project...
    goto :full_build
)

REM Simple incremental check: run Maven compile to see if anything changed
echo Checking for source code changes with Maven compile...
call mvn compile -q >nul 2>&1
if %errorlevel% neq 0 (
    echo Maven compile indicates changes or issues. Rebuilding...
    goto :full_build
)

REM Check if target/classes is newer than JAR (simple heuristic)
set CLASSES_DIR=%PROJECT_ROOT%resource-server\target\classes
if exist "%CLASSES_DIR%" (
    echo Comparing compilation timestamps...
    
    REM Use PowerShell to compare file times more reliably
    powershell -Command "if ((Get-Item '%CLASSES_DIR%').LastWriteTime -gt (Get-Item '%JAR_FILE%').LastWriteTime) { exit 1 } else { exit 0 }"
    if %errorlevel% equ 1 (
        echo Source code changes detected. Rebuilding JAR...
        goto :full_build
    ) else (
        echo No recent changes detected. Using existing JAR file.
        goto :start_server
    )
) else (
    echo Classes directory not found. Building project...
    goto :full_build
)

:full_build
echo.
echo Building project with Maven...
echo.
call mvn clean package -DskipTests
if not %errorlevel%==0 (
    echo Error: Maven build failed
    pause
    exit /b 1
)
echo Build completed successfully
echo.

REM Check again if JAR file exists after build
if not exist "%JAR_FILE%" (
    echo Error: JAR file still not found after build: %JAR_FILE%
    pause
    exit /b 1
)

:start_server
echo Starting Jan Backend Server...
echo JAR file: %JAR_FILE%
echo.
echo Server will start on: http://localhost:48080
echo API documentation: http://localhost:48080/doc.html
echo.

REM Start the Spring Boot application
java -jar "%JAR_FILE%"

REM If we reach here, the server has stopped
echo.
echo Server has stopped.
pause